package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.DTO.UserRegisterDTO;
import com.example.demo.DTO.UserWebLoginDTO;
import com.example.demo.Mapper.UserMapper;
import com.example.demo.entity.WebUser;
import com.example.demo.result.Result;
import com.example.demo.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, WebUser> implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 检查用户是否存在
     * @param username
     * @return
     */
    @Override
    public WebUser checkUserExists(String username) {
        //判断使用用户名查询用户
        QueryWrapper<WebUser> wrapper=new QueryWrapper<>();
        wrapper.lambda()
                .eq(WebUser::getUsername,username);
        return userMapper.selectOne(wrapper);
    }

    /**
     * 用户注册
     * @param userRegisterDTO
     * @return
     */
    @Override
    public Result<String> userRegister(UserRegisterDTO userRegisterDTO) {
        WebUser webUser = WebUser.builder()
                .name(userRegisterDTO.getName())
                .username(userRegisterDTO.getUsername())
                .password(userRegisterDTO.getPassword())
                .phone(userRegisterDTO.getPhone())
                .build();
        userMapper.insert(webUser);
        return Result.success("注册成功");
    }

    @Override
    public WebUser webLogin(UserWebLoginDTO userWebLoginDTO) {
        String username = userWebLoginDTO.getUsername();
        String password = userWebLoginDTO.getPassword();

        //通过web端账号密码查询用户信息
        //1、判断用户是否存在
        WebUser webUser = checkUserExists(username);


        //2、判断密码是否正确
        if(!password.equals(userWebLoginDTO.getPassword())){
            return null;
        }

        return webUser;
    }
}
